package com.tgy.myplus.基础学习.Thread.线程协作;

/**
 * @author 送你一块二向箔
 * @date 2021/11/09 14:06
 */

/**
 * 测试管程法
 * 生产者 消费者 缓冲区
 */
public class TestPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        new Thread(new Producer(synContainer)).start();
        new Thread(new Consumer(synContainer)).start();

    }
}


//生产者
class Producer implements Runnable {
    SynContainer container;

    public Producer(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("生产了第"+(i+1)+"产品");
            container.push(new Toy(i));
        }
    }
}

//消费者
class Consumer implements Runnable {
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 90; i++) {
            System.out.println("消费了第"+container.pop().id+"产品");
            ;
        }
    }
}


//产品
class Toy {
	int id;

    public Toy(int id) {
        this.id = id;
    }
}

//缓冲区
class SynContainer{
    //需要一个容器大小
    Toy[] toys =new Toy[10];

    int count = 0;

    //生产者放入产品
    public synchronized void push(Toy toy) {
        //count++;
        //System.out.println(count);
        //System.out.println(toys.length);
        //如果容器满了，就需要等待消费者
        if (count==toys.length){
            //通知消费者消费,生产停止
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }else{
            toys[count] = toy;
            count++;
            //如果容器没满就需要放入产品，通知生产者生产
            this.notifyAll();
        }
    }
    //消费者消费产品
    public synchronized Toy pop() {
        if(count == 0){
            //停止消费，通知生产者
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //消费，并通知生产者
        count--;
        Toy toy = toys[count];
        this.notifyAll();
        return toy;
    }
}


